///**
// * @author: Niimp
// * @date: 2023/12/19 8:10
// * @statement:
// */
//package com.dmgis.hndz.Service.impl;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import com.baomidou.mybatisplus.core.toolkit.StringUtils;
//import com.dmgis.entity.*;
//import com.dmgis.hndz.Service.EarlyWaringService;
//import com.dmgis.hndz.common.utils.DmgisUtils;
//import com.dmgis.hndz.mapper.EarlyWaringMapper;
//import com.dmgis.hndz.pojo.ColorAndNameDto;
//import com.dmgis.hndz.pojo.ColorAndPos;
//import com.dmgis.hndz.pojoVo.PointSetVo;
//import com.dmgis.service.DmServiceConnector;
//import com.dmgis.service.MapXML;
//import org.apache.poi.util.Units;
//import org.apache.poi.xwpf.usermodel.*;
//import org.apache.xmlbeans.XmlCursor;
//import org.ini4j.Ini;
//import org.ini4j.Wini;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.boot.system.ApplicationHome;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//import org.springframework.stereotype.Service;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.annotation.Resource;
//import java.io.*;
//import java.text.ParseException;
//import java.text.SimpleDateFormat;
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.dmgis.hndz.common.utils.DmgisUtils.getCountryMap;
//
//@Service
//public class EarlyWaringServiceImpl implements EarlyWaringService {
//    @Value("${dmgis.ip}")
//    private String dmgisIp;
//
//    @Value("${dmgis.port}")
//    private String dmgisPort;
//
//    @Value("${dmgis.serveName}")
//    private String serveName;
//
//    @Value("${filePath.active}")
//    private String active;
//    @Resource
//    private EarlyWaringMapper earlyWaringMapper;
//
//
//    @Override
//    public Map<String, String> getCountry(List<PointSetVo> pointSetVoList) throws UnsupportedEncodingException {
//        Map<String, String> map = new HashMap<>();
//
//        Map<String, List<PointSetVo>> typeAndYjqMap = new HashMap<>();
//        for (PointSetVo yjqDto : pointSetVoList) {
//            List<PointSetVo> pointSetVoList1 = new ArrayList<>();
//            if (typeAndYjqMap.containsKey(yjqDto.getType())) {
//                pointSetVoList1 = typeAndYjqMap.get(yjqDto.getType());
//            }
//            pointSetVoList1.add(yjqDto);
//            typeAndYjqMap.put(yjqDto.getType(), pointSetVoList1);
//        }
//
//        for (Map.Entry<String, List<PointSetVo>> entry : typeAndYjqMap.entrySet()) {
//            List<String[]> posList = new ArrayList<>();
//            String type = entry.getKey();
//            List<PointSetVo> pointSetVoList1 = entry.getValue();
//            for (PointSetVo yjqDto : pointSetVoList1) {
//                posList.add(yjqDto.getPos());
//            }
//            Map<String, String> layerCountry = getLayerCountry(posList, type);
//            Set<Map.Entry<String, String>> entries = layerCountry.entrySet();
//            for (Map.Entry<String, String> stringStringEntry : entries) {
//                if (!map.containsKey(stringStringEntry.getKey())) {
//                    map.put(stringStringEntry.getKey(), stringStringEntry.getValue());
//                } else {
//                    String oldType = map.get(stringStringEntry.getKey());
//                    int oldTypeNumber = Integer.parseInt(oldType);
//                    int newTypeNumber = Integer.parseInt(stringStringEntry.getValue());
//                    if (newTypeNumber > oldTypeNumber) {
//                        map.put(stringStringEntry.getKey(), stringStringEntry.getValue());
//                    }
//                }
//            }
//        }
//
////        for (YjqDto yjqDto : yjqDtoList) {
////            Map<String, String> layerCountry = getLayerCountry(yjqDto.getPos(), yjqDto.getType());
////            Set<Map.Entry<String, String>> entries = layerCountry.entrySet();
////            for (Map.Entry<String, String> entry : entries) {
////                if (!map.containsKey(entry.getKey())) {
////                    map.put(entry.getKey(), entry.getValue());
////                } else {
////                    String oldType = map.get(entry.getKey());
////                    int oldTypeNumber = Integer.parseInt(oldType);
////                    int newTypeNumber = Integer.parseInt(entry.getValue());
////                    if (newTypeNumber > oldTypeNumber) {
////                        map.put(entry.getKey(), entry.getValue());
////                    }
////                }
////            }
////        }
//
//        Set<Map.Entry<String, String>> entries = map.entrySet();
//        for (Map.Entry<String, String> entry : entries) {
//            String value = "";
//            switch (entry.getValue()) {
//                case "0":
//                    value = "风险较大";
//                    break;
//                case "1":
//                    value = "风险大";
//                    break;
//                case "2":
//                    value = "风险很大";
//                    break;
//                case "3":
//                    value = "风险很大";
//                    break;
//                case "4":
//                    value = "风险很大";
//                    break;
//            }
//            entry.setValue(value);
//        }
//        return map;
//    }
//
//    /**
//     * 多边形查询乡镇点
//     *
//     * @param posList 点集
//     * @param type
//     * @return
//     * @throws UnsupportedEncodingException
//     */
//    private Map<String, String> getLayerCountry(List<String[]> posList, String type) throws UnsupportedEncodingException {
//        System.out.println(System.currentTimeMillis() / 1000);
//        StringBuilder sb = new StringBuilder();
//        for (String[] pos : posList) {
//            for (String po : pos) {
//                String[] posStr = po.split(" ");
//                DmMapPoint dmMapPoint = DmgisUtils.wgsToLbt(Double.parseDouble(posStr[0]), Double.parseDouble(posStr[1]));
//                sb.append(dmMapPoint.getX()).append(" ").append(dmMapPoint.getY()).append(";");
//            }
//            sb.deleteCharAt(sb.length() - 1);
//            sb.append("*");
//        }
//        sb.deleteCharAt(sb.length() - 1);
//
//        System.out.println(System.currentTimeMillis() / 1000);
//        DmServiceConnector conn = new DmServiceConnector(dmgisIp, dmgisPort);
//        String xml = "";
//        //属性服务
//        DmFeatureMapService dmFeatureMapService = new DmFeatureMapService();
//        dmFeatureMapService.setStrLayerName("乡界面");
//        DmFeatureParam dmFeatureParam = new DmFeatureParam();
//        dmFeatureParam.setAttribute(1);
//        dmFeatureParam.setFeatureLimit(0);
//        dmFeatureMapService.setParam(dmFeatureParam);
//        dmFeatureMapService.setType("0");
//        DmSql dmSql = new DmSql();
//        dmSql.setStrPos(sb.toString());
//        dmFeatureMapService.setM_sql(dmSql);
//        xml = dmFeatureMapService.getXmlString();
//        System.out.println(xml);
//        String res = conn.getServiceXml(serveName, 2, xml);
//        System.out.println(res);
//        MapXML mapXML = new MapXML();
//        DmGetFeature feature = mapXML.dmGetFeatureInfo(res);
//        Map<String, String> countryMap = new HashMap<>();
//        List<DmObj> map = feature.getObjset();
//        for (DmObj obj : map) {
//            List<DmRcoVal> rec = obj.getRec();
//            for (DmRcoVal dmRcoVal : rec) {
//                if (dmRcoVal.getFldName().equals("NAME")) {
//                    countryMap.put(dmRcoVal.getFldVal(), type);
//                    break;
//                }
//            }
//        }
//        return countryMap;
//    }
//
//
//
//
////    @Override
////    public Object createProduct(Integer issueNum,
////                                String userName,
////                                String yjType,
////                                String sXType,
////                                String date,
////                                String timeChar,
////                                Integer nTimes,
////                                String colorAndPos,
////                                String posStr,
////                                MultipartFile[] images,
////                                String layerName,
////                                String dlData) throws IOException, NoSuchFieldException, IllegalAccessException, ParseException {
////        //模板路径
////        String templatePath;
////        //产品路径
////        String targetPath;
////        //配置文件路径
////        String configFilePath;
////
////        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
////        if (active.equals("dev")) {
////            templatePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
////                    "\\src\\main\\resources\\Documents\\风险预警模板\\山洪灾害气象风险预警模板.docx";
////            targetPath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
////                    "\\src\\main\\resources\\temp\\山洪灾害气象风险预警文档.docx";
////            configFilePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
////                    "\\src\\main\\resources\\Documents\\风险预警模板\\预警内容.ini";
////        } else {
////            templatePath = applicationHome.getSource().getParentFile() +
////                    "\\resource\\Documents\\风险预警模板\\山洪灾害气象风险预警模板.docx";
////            targetPath = applicationHome.getSource().getParentFile() +
////                    "\\resources\\temp\\山洪灾害气象风险预警文档.docx";
////            configFilePath = applicationHome.getSource().getParentFile() +
////                    "\\resources\\Documents\\风险预警模板\\预警内容.ini";
////        }
//////        System.out.println("模板路径"+templatePath);
////
////        //json字符串转换为对象列表
////        List<ColorAndPos> posList = JSON.parseArray(colorAndPos, ColorAndPos.class);
////        List<DmObj> map = new ArrayList<>();
////        Map<Integer, List<ColorAndNameDto>> colorAndNameMap = new HashMap<>();
////        //获取预警区内乡镇数据
////        for (ColorAndPos typeAndPos : posList) {
////            String type = typeAndPos.getColor();
//////            if (type.equals("0")) {
//////                continue;
//////            }
////            String color = "";
////            switch (type) {
////                case "0":
////                    color = "黄色";
////                    break;
////                case "1":
////                    color = "橙色";
////                    break;
////                case "2":
////                    color = "红色";
////                    break;
////            }
////            //多边形查询乡界面
////            map = getCountryMap(dmgisIp, dmgisPort, serveName, typeAndPos.getPos());
////
////            for (DmObj obj : map) {
////                List<DmRcoVal> rec = obj.getRec();
////                for (DmRcoVal dmRcoVal : rec) {
////                    String fldName = dmRcoVal.getFldName();
////                    if (fldName.equals("NAME")) {
////                        ColorAndNameDto colorAndNameDto = new ColorAndNameDto();
////                        colorAndNameDto.setCounty("义乌");
////                        colorAndNameDto.setCountry(dmRcoVal.getFldVal());
////                        colorAndNameDto.setType(Integer.parseInt(type));
////                        colorAndNameDto.setColor(color);
////                        List<ColorAndNameDto> colorAndNameDtoList = null;
////                        if (colorAndNameMap.containsKey(Integer.parseInt(type))) {
////                            colorAndNameDtoList = colorAndNameMap.get(Integer.parseInt(type));
////                        } else {
////                            colorAndNameDtoList = new ArrayList<>();
////                        }
////                        colorAndNameDtoList.add(colorAndNameDto);
////                        List<ColorAndNameDto> collect = colorAndNameDtoList.stream().distinct().collect(Collectors.toList());
////                        colorAndNameMap.put(Integer.parseInt(type), collect);
////                    }
////                }
////            }
////        }
////
////
////        //读取配置文件获取正文
////        Wini ini = new Wini(new BufferedReader(new InputStreamReader(new FileInputStream(configFilePath), "GBK")));
////        Ini.Section section = ini.get("DOCS");
////        String docType = "";
////        if (colorAndNameMap.containsKey(0) && !colorAndNameMap.containsKey(1) && !colorAndNameMap.containsKey(2)) {
////            docType = section.get("doc1");
////        } else if (!colorAndNameMap.containsKey(0) && colorAndNameMap.containsKey(1) && !colorAndNameMap.containsKey(2)) {
////            docType = section.get("doc2");
////        } else if (!colorAndNameMap.containsKey(0) && !colorAndNameMap.containsKey(1) && colorAndNameMap.containsKey(2)) {
////            docType = section.get("doc3");
////        } else if (colorAndNameMap.containsKey(0) && colorAndNameMap.containsKey(1) && !colorAndNameMap.containsKey(2)) {
////            docType = section.get("doc12");
////        } else if (colorAndNameMap.containsKey(0) && !colorAndNameMap.containsKey(1) && colorAndNameMap.containsKey(2)) {
////            docType = section.get("doc13");
////        } else if (!colorAndNameMap.containsKey(0) && colorAndNameMap.containsKey(1) && colorAndNameMap.containsKey(2)) {
////            docType = section.get("doc23");
////        } else if (colorAndNameMap.containsKey(0) && colorAndNameMap.containsKey(1) && colorAndNameMap.containsKey(2)) {
////            docType = section.get("doc123");
////        }
////        //一级区县内容
////        StringBuilder country1 = new StringBuilder();
////        //二级区县内容
////        StringBuilder country2 = new StringBuilder();
////        //三级区县内容
////        StringBuilder country3 = new StringBuilder();
////
////        List<ColorAndNameDto> colorAndNameDtoListAll = new ArrayList<>();
////        if (colorAndNameMap.containsKey(0)) {
////            List<ColorAndNameDto> colorAndNameDtoList = colorAndNameMap.get(0);
////            colorAndNameDtoListAll.addAll(colorAndNameDtoList);
////            for (ColorAndNameDto colorAndNameDto : colorAndNameDtoList) {
////                country1.append(colorAndNameDto.getCountry()).append(",");
////            }
////            country1.deleteCharAt(country1.length() - 1);
////        }
////        if (colorAndNameMap.containsKey(1)) {
////            List<ColorAndNameDto> colorAndNameDtoList = colorAndNameMap.get(1);
////            colorAndNameDtoListAll.addAll(colorAndNameDtoList);
////            for (ColorAndNameDto colorAndNameDto : colorAndNameDtoList) {
////                country2.append(colorAndNameDto.getCountry()).append(",");
////            }
////            country2.deleteCharAt(country2.length() - 1);
////
////        }
////        if (colorAndNameMap.containsKey(2)) {
////            List<ColorAndNameDto> colorAndNameDtoList = colorAndNameMap.get(2);
////            colorAndNameDtoListAll.addAll(colorAndNameDtoList);
////            for (ColorAndNameDto colorAndNameDto : colorAndNameDtoList) {
////                country3.append(colorAndNameDto.getCountry()).append(",");
////            }
////            country3.deleteCharAt(country3.length() - 1);
////        }
////        //替换正文内容
////        docType = docType.replace("[一级区县]", country1.toString());
////        docType = docType.replace("[二级区县]", country2.toString());
////        docType = docType.replace("[三级区县]", country3.toString());
////        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
////        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日HH时");
////        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
////        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年MM月dd日");
////        Date date1 = sdf.parse(date);
////        docType = docType.replace("[发布时间]", sdf1.format(new Date()));
////        docType = docType.replace("[批号]", String.valueOf(issueNum));
////        docType = docType.replace("[预警起报点]", sdf3.format(date1) + timeChar + "时");
////        docType = docType.replace("[预警时长]", String.valueOf(nTimes));
////        //设置点集合区县内容
////        SlWarning slWarning = new SlWarning();
////        slWarning.setPos(posStr);
////        slWarning.setGradearea3(country1.toString());
////        slWarning.setGradearea4(country2.toString());
////        slWarning.setGradearea5(country3.toString());
////        //解析地理分析数据
////        List<Object> layerObjectList = new ArrayList<>();
////        if (StringUtils.isNotBlank(dlData) && StringUtils.isNotBlank(layerName)) {
////            try {
////                List<LayerRcoDto> LayerRcoDtoList = JSON.parseArray(dlData, LayerRcoDto.class);
////                Class layerClass = getLayerClass(layerName);
////                for (LayerRcoDto layerRcoDto : LayerRcoDtoList) {
////                    JSONObject rcoValObject = (JSONObject) layerRcoDto.getRcoValObject();
////                    Object javaObject = JSON.toJavaObject(rcoValObject, layerClass);
////                    layerObjectList.add(javaObject);
////                }
////            } catch (Exception e) {
////                System.err.println("地理分析数据解析错误");
////            }
////        }
////
////        //生成文档
////        try (
////                InputStream templateInputStream = new FileInputStream(templatePath);
////                OutputStream targetOutputStream = new FileOutputStream(targetPath);
////                XWPFDocument document = new XWPFDocument(templateInputStream);
////                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
////        ) {
////
////            //段落替换
////            String[] placeholders = new String[]{"[文件号]", "[时间1]", "[预警内容]"};
////            //替换内容
////            String[] replacements = new String[]{String.valueOf(issueNum), sdf3.format(date1) + timeChar + "时" + "00分", docType};
////
////            List<XWPFParagraph> paragraphs = document.getParagraphs();
////
////
////            for (int i = 0; i < paragraphs.size(); i++) {
////                XWPFParagraph paragraph = paragraphs.get(i);
////                String text = paragraph.getText();
////                replaceTextInParagraph(paragraph, placeholders, replacements);
////                //插入图片
////                if (StringUtils.isNotBlank(text) && text.contains("[图片]")) {
////                    //获取下标
////                    XmlCursor cursor = paragraph.getCTP().newCursor();
////                    XWPFParagraph newPara = document.insertNewParagraph(cursor);
////                    newPara.setAlignment(ParagraphAlignment.CENTER);//居中
////                    XWPFRun newParaRun = newPara.createRun();
////                    for (MultipartFile image : images) {
////                        //插入图片
////                        newParaRun.addPicture(image.getInputStream(), XWPFDocument.PICTURE_TYPE_PNG, "image.png,", Units.toEMU(420), Units.toEMU(270));
////                    }
////                    document.removeBodyElement(document.getPosOfParagraph(paragraph));
////                }
////                //插入预警区表格
////                if (StringUtils.isNotBlank(text) && text.contains("[表1]")) {
////                    //获取下标
////                    XmlCursor cursor = paragraph.getCTP().newCursor();
////                    XWPFTable table = document.insertNewTbl(cursor);
////                    //添加表头
////                    XWPFTableRow row_0 = table.getRow(0);
////                    row_0.getCell(0).setText("区县");
////                    row_0.addNewTableCell().setText("乡镇");
////                    row_0.addNewTableCell().setText("预警等级");
////                    colorAndNameDtoListAll.forEach(country -> {
////                        XWPFTableRow dataRow = table.createRow();
////                        dataRow.getCell(0).setText(country.getCounty());
////                        dataRow.getCell(1).setText(country.getCountry());
////                        dataRow.getCell(2).setText(country.getColor());
////                    });
////                    setTableLocation(table, "center");
////                    setCellLocation(table, "CENTER", "center");
////                    document.removeBodyElement(document.getPosOfParagraph(paragraph));
////                }
////                //插入地理分析数据表格
////                if (layerObjectList.size() > 0 && StringUtils.isNotBlank(text) && text.contains("[预警信息表]")) {
////                    System.out.println("插入地理分析表格数据");
////                    //获取下标
////                    XmlCursor cursor = paragraph.getCTP().newCursor();
////                    XWPFTable table = document.insertNewTbl(cursor);
////                    //插入图层表格数据
////                    insertTablaLayerData(layerName, layerObjectList, table);
////                    setTableLocation(table, "center");
////                    setCellLocation(table, "CENTER", "center");
////                    document.removeBodyElement(document.getPosOfParagraph(paragraph));
////
////                }
////            }
////            // 将生成的文档保存到输出文件
////            document.write(targetOutputStream);
////
////            //获取文档名称
////            String productName = sdf1.format(date1) + "第" + issueNum + "期山洪灾害预警文档.docx";
////            //插入山洪预警表数据
////
////            slWarning.setDatechar(sdf.parse(sdf2.format(date1)));
////            slWarning.setTimechar(timeChar);
////            slWarning.setNtimes(nTimes);
////            slWarning.setState(1);
////            slWarning.setFirst(userName);
////            slWarning.setSecond(userName);
////            slWarning.setThird(userName);
////            slWarning.setIsrelease(0);
////            slWarning.setShflag(0);
////            slWarning.setForetype(0);
////            slWarning.setWarningtype(sXType);
////            slWarning.setDocpath(productName);
////            slWarning.setWarnResult(docType);
////            slWarningMapper.insert(slWarning);
////            //保存基本产品表数据
////            BaseProduct baseProduct = new BaseProduct();
////            baseProduct.setProductname(productName);
////            baseProduct.setProducttype(yjType + sXType);
////            baseProduct.setForecasttime(date1);
////            baseProduct.setMaketime(new Date());
////            baseProduct.setBindid(slWarning.getDocid());
////            baseProduct.setMaker(userName);
////            baseProductMapper.insert(baseProduct);
////            byte[] buffer = new byte[1024];
////            int bytesRead;
////            FileInputStream inputStream = new FileInputStream(targetPath);
////            while ((bytesRead = inputStream.read(buffer)) != -1) {
////                byteArrayOutputStream.write(buffer, 0, bytesRead);
////            }
////            byte[] byteArray = byteArrayOutputStream.toByteArray();
////            //保存到mongodb库中
////            HyDocFile hyDocFile = new HyDocFile();
////            hyDocFile.setData(byteArray);
////            hyDocFile.setTable_name("base_product");
////            hyDocFile.setId(String.valueOf(baseProduct.getId()));
////            mongoTemplate.save(hyDocFile);
////            // 设置前端响应
////            HttpHeaders headers = new HttpHeaders();
////            headers.setContentDispositionFormData("attachment", "山洪预警文档.docx");
////            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
////            headers.setContentLength(byteArray.length);
//////            wordToPdf(targetPath,targetPdfPath);
////            return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);
////        } catch (Exception e) {
////            e.printStackTrace();
////            System.err.println("文档生成失败");
////        }
////
////        return null;
////    }
//
//
//
//}
//
//
